package com.fromdev.automation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.SeleneseTestCase;

public class SquidooHopper extends SeleneseTestCase {
	private String PASSWORD = "pass";
	private String UUSER_NAME = "username";

	@Before
	public void setUp() throws Exception {
		selenium = new DefaultSelenium("localhost", 4444, "*googlechrome",
				"http://www.squidoo.com");
		initConfig();

		// selenium = new DefaultSelenium("localhost", 4444,
		// "*firefox","http://www.squidoo.com");
		selenium.start();
	}

	private void initConfig() throws IOException {
		Properties prop = new Properties();
		prop.load(this.getClass().getClassLoader()
				.getResourceAsStream("config.properties"));
		PASSWORD = prop.getProperty("user.password");
		UUSER_NAME = prop.getProperty("user.name");
	}

	@Test
	public void testSquidooHopper() throws Exception {
		int sleepTime = 0;
		int exploreCategory = 0;
		int freshLenseId = 0;

		selenium.open("/");
		selenium.waitForPageToLoad("30000");
		try {
			login();

			Thread.sleep(TimeUtil.getTypingTimeSeconds());

			// repeat other steps until favorable
			while (true) {
				try {
					if (!(TimeUtil.isWeekDay() && TimeUtil.isWorkingHour())) {
						// Go to home page.
						System.out.println("Strating with home");
						goToHome();

						// pick a random category to explore
						exploreCategory = TimeUtil.getNumberBetween(1, 12);
						System.out.println("Exploring category " + exploreCategory);
						exploreCategories(exploreCategory);

						freshLenseId = TimeUtil.getNumberBetween(1, 10);
						System.out.println("Opening lens " + freshLenseId);
						openFreshLense(freshLenseId);
						readFullPage();
						// Randomly like a lense
						if (TimeUtil.getNumberBetween(1, 25) % 3 == 0) {
							System.out.println("I dont like this lense");
						} else {
							likeLense();
							// Voting on poll as well if exists
							voteOnPoll();
						}
					} else {
						System.out.println("Nothing to do");
					}
					sleepTime = TimeUtil.getTypingTimeSeconds() * 15;
					System.out.println("Done: Going to sleep for " + sleepTime);
					Thread.sleep(sleepTime);
				} catch (Exception e) {
					e.printStackTrace();
					System.out
							.println("Failed for: exploreCategory:"
									+ exploreCategory + " FreshLenseId:"
									+ freshLenseId);
					if (!goToHome()) {
						System.out
								.println("No Home Page link available. Finishing job.");
						break;
					}
				} finally {
					System.out.println("Finally Done one round");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Failed for: exploreCategory:" + exploreCategory
					+ " FreshLenseId:" + freshLenseId);
		}

	}

	private void login() throws InterruptedException {
		if (selenium.isElementPresent("//*[@id='toolbar_login']")) {
			System.out.println("Opening Login page");
			selenium.click("id=toolbar_login");
			selenium.waitForPageToLoad("30000");
			Thread.sleep(TimeUtil.getTypingTimeSeconds());
			selenium.click("id=email_address");
			selenium.type("id=email_address", UUSER_NAME);
			Thread.sleep(TimeUtil.getTypingTimeSeconds());
			selenium.type("id=member_password", PASSWORD);
			Thread.sleep(TimeUtil.getTypingTimeSeconds());
			selenium.click("id=loginButton");
			selenium.waitForPageToLoad("30000");
			System.out.println("Just Logged in");

		}
		/*
		 * if (selenium.isElementPresent(
		 * "//*[@id='dashboard-table']/table/tbody/tr[1]/td[5]/a[1]")) {
		 * selenium
		 * .click("//*[@id='dashboard-table']/table/tbody/tr[1]/td[5]/a[1]");
		 * selenium.waitForPageToLoad("30000"); }
		 */

		int sleepTime;
		sleepTime = TimeUtil.getTypingTimeSeconds();
		System.out.println("login: Going to sleep for " + sleepTime);
		Thread.sleep(sleepTime);
	}

	private void exploreCategories(int exploreCategory)
			throws InterruptedException {
		List exploreCategoryXPaths = new ArrayList();
		exploreCategoryXPaths.add("/html/body/section[1]/div/header/div/a["
				+ exploreCategory + "]");
		exploreCategoryXPaths.add("//*[@id='explore_box']/ul/li["
				+ exploreCategory + "]/a");

		// likeButtonXPaths.add("//*[@id='lens_header']/div[3]/ul/li[2]/a");

		String exploreCategoryXPath = "//*[@id='explore_box']/ul/li["
				+ exploreCategory + "]/a";
		SeleniumUtil.doClick(selenium, exploreCategoryXPaths);
		/*
		 * int sleepTime;
		 * 
		 * if (selenium.isElementPresent(exploreCategoryXPath)) {
		 * selenium.click(exploreCategoryXPath);
		 * selenium.waitForPageToLoad("30000"); sleepTime =
		 * TimeUtil.getTypingTimeSeconds();
		 * System.out.println("exploreCategories: Going to sleep for " +
		 * sleepTime); Thread.sleep(sleepTime);
		 * System.out.println("Selected Explore Category"); }
		 */
	}

	private void readFullPage() throws InterruptedException {
		int sleepTime;
		String footerXPath = "//*[@id='footer']/div[1]/div[1]";
		if (selenium.isElementPresent(footerXPath)) {
			selenium.click(footerXPath);
			// selenium.waitForPageToLoad("30000");
			sleepTime = TimeUtil.getTypingTimeSeconds() + 15000;
			System.out.println("readFullPage: Reading the Lense till footer "
					+ sleepTime);
			Thread.sleep(sleepTime);
			System.out.println("Read the Lense till footer ");
		}
	}

	private void openFreshLense(int freshLenseId) throws InterruptedException {

		List lensXPaths = new ArrayList();
		lensXPaths.add("//*[@id='home_grid']/div[" + freshLenseId + "]/div/div[1]/a");
		lensXPaths.add("//*[@id='fresh_lenses']/li["
				+ freshLenseId + "]/a");
		SeleniumUtil.doClick(selenium, lensXPaths);
		/*
		 * int sleepTime; if
		 * (selenium.isElementPresent("//*[@id='fresh_lenses']/li[" +
		 * freshLenseId + "]/a")) { selenium.click("//*[@id='fresh_lenses']/li["
		 * + freshLenseId + "]/a"); selenium.waitForPageToLoad("30000");
		 * sleepTime = TimeUtil.getTypingTimeSeconds();
		 * System.out.println("openFreshLense: Going to sleep for " +
		 * sleepTime); Thread.sleep(sleepTime);
		 * System.out.println("Clicked on Fresh lense"); }
		 */
	}

	private void likeLense() throws InterruptedException {
		List likeButtonXPaths = new ArrayList();
		likeButtonXPaths.add("//*[@id='share_wrap']/ul[1]/li[1]/a");
		likeButtonXPaths.add("//*[@id='share_wrap']/ul[1]/li[1]/a");
		likeButtonXPaths.add("//*[@id='lens_header']/div[3]/ul/li[2]/a");

		if (!SeleniumUtil.doClick(selenium, likeButtonXPaths)) {
			System.out
					.println("Can not find a like button. Time to update code. ["
							+ selenium.getLocation() + "]");
		}
		/*
		 * int sleepTime; String likeStyle1 =
		 * "//*[@id='share_wrap']/ul[1]/li[1]/a"; String likeStyle2 =
		 * "//*[@id='left_col']/article/header/div[3]/ul/li[2]/a/span[2]";
		 * boolean likeButtonFound = false; try { if
		 * (selenium.isElementPresent(likeStyle1)) {
		 * System.out.println("The like style is #1");
		 * selenium.click(likeStyle1); // selenium.waitForPageToLoad("30000");
		 * sleepTime = TimeUtil.getTypingTimeSeconds(); System.out
		 * .println("likeLense: Going to sleep for " + sleepTime);
		 * Thread.sleep(sleepTime); System.out.println("I like this lense");
		 * likeButtonFound = true; } } catch (Exception e) {
		 * System.out.println("Error : at like button 1 " + e.getMessage());
		 * likeButtonFound = false; } try { if
		 * (selenium.isElementPresent(likeStyle2)) {
		 * System.out.println("The like style is #2");
		 * System.out.println("I like this lense"); likeButtonFound = true; } }
		 * catch (Exception e) { System.out.println("Error : at like button 2 "
		 * + e.getMessage()); likeButtonFound = false; }
		 * 
		 * if (!likeButtonFound) { System.out
		 * .println("Can not find a like button. Time to update code."); }
		 */
	}

	private void voteOnPoll() throws InterruptedException {
		int sleepTime;
		String poll = "//*[@id='quickpoll']";
		if (selenium.isElementPresent(poll)) {
			System.out.println("Found a poll lets vote...");
			String pollOption1 = "//*[@id='quickpoll']/div[2]/div/div[1]/div/label/input";
			String pollOption2 = "//*[@id='quickpoll']/div[2]/div/div[2]/div/label/input";
			String voteButton = "//*[@id='quickpoll']/div[2]/p/span";
			if (selenium.isElementPresent(pollOption1)
					&& selenium.isElementPresent(voteButton)) {
				if ((Math.random() * 10) % 2 == 0) {
					System.out.println("Voted for option 1");
					selenium.click(pollOption1);
				} else {
					System.out.println("Voted for option 2");
					selenium.click(pollOption2);
				}
				// selenium.waitForPageToLoad("30000");

				sleepTime = TimeUtil.getTypingTimeSeconds();
				Thread.sleep(sleepTime);
				selenium.click(voteButton);
				Thread.sleep(sleepTime);
			} else {
				System.out
						.println("Can not find a vote button. Time to update code.");
			}
		}
	}

	private boolean goToHome() throws Exception {
		int sleepTime = TimeUtil.getTypingTimeSeconds();
		List homePageXPathList = new ArrayList();
		homePageXPathList.add("//*[@id='header']/h4/a");
		homePageXPathList.add("//*[@id='dash_logo']/a");
		homePageXPathList.add("//*[@id='header']/h1/a");

		SeleniumUtil.doClick(selenium, homePageXPathList);

		try {
			selenium.open("/");
			selenium.waitForPageToLoad("30000");
			System.out.println("/ to Home Page");
			System.out.println("goToHome: Going to sleep for " + sleepTime);
			Thread.sleep(sleepTime);
			return true;
		} catch (Exception e) {
			System.out.println("Cant find home page #3");
		} finally {

		}
		System.out.println("Cant find home page anywhere");
		return false;
	}

	@After
	public void tearDown() throws Exception {
		selenium.stop();
	}
}
